package com.search.bturls;

import com.search.ThreadPool.ThreadService.GrabThread;
import com.search.commons.CommonPage;
import com.search.commons.SearchConstants;
import com.search.commons.SearchCore;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Tonight on 2017/4/5.
 */
@Service
public class BturlsService {

    @Autowired
    GrabThread grabThread;

    //微信专用（性能开销巨大 谨慎使用）
    public String getBtDataList(String content)
    {
        StringBuffer sb = null;

        Map<String,String> downloadUrl = null;
        try {
            String url = SearchConstants.BT_BTURLS_URL + "/search/" + content + "_ctime_1.html";

            Document document = SearchCore.getHtmlDom(url);

            if(document != null)
            {
                Element element = document.body();

                Integer count = element.getElementsByClass("T1").size();

                if(count != null && count > 0)
                {
                    sb = new StringBuffer();
                    downloadUrl = new HashMap<>();
                    CountDownLatch CountDownLatch = new CountDownLatch(count);
                    grabThread.setCount(CountDownLatch);
                    grabThread.setDownloadUrl(downloadUrl);
                    element.getElementsByClass("T1").forEach
                            (
                                    item ->
                                    {
                                        Element  elementItem = item.children().get(0);
                                        //启动异步任务
                                        grabThread.executeAsyncTaskRun(SearchConstants.BT_BTURLS_URL + elementItem.attr("href"),elementItem.html().replaceAll("<span class=\"highlight\">|</span>|\\x0a",""));
                                    }
                            );

                    //等待子线程执行完毕后，主线程才继续执行
                    CountDownLatch.await();

                    for (Map.Entry<String, String> entry : downloadUrl.entrySet())
                    {
                        sb.append(entry.getKey() + "\n");
                        sb.append(entry.getValue() + "\n");
                    }
                }
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return sb == null ? "没有搜索到你想要的结果！" : sb.toString();
    }

    //微信专用（性能开销巨大 谨慎使用）
    public CommonPage<Bturls> getBtDataList(String content, Integer currentPage)
    {
        CommonPage<Bturls> commonPage = new CommonPage<>();

        commonPage.setCode(SearchConstants.CODE_SUCCESS);

        commonPage.setMessage("数据检索成功！");

        List<Bturls> list = null;
        try {
            if(currentPage == null)
            {
                currentPage = 1;
            }
            String url = SearchConstants.BT_BTURLS_URL + "/search/" + content + "_ctime_" + currentPage + ".html";

            Document document = SearchCore.getHtmlDom(url);

            if(document != null)
            {
                Element element = document.body();

                Integer count = element.getElementsByClass("BotInfo").size();

                if(count != null && count > 0)
                {
                    list = new ArrayList<>();

                    for(Element item : element.getElementsByClass("BotInfo"))
                    {
                        //获取种子标题
                        Element  elementFileNameItem = item.children().first();
                        Bturls bturls = new Bturls();
                        //文件名
                        bturls.setFileName(elementFileNameItem.html());
                        Element  elementFileInfoItem = item.children().get(1);
                        //创建时间
                        bturls.setCreateDate(elementFileInfoItem.children().first().html());
                        //文件大小
                        bturls.setFileSize(elementFileInfoItem.children().get(1).html());
                        //热度
                        bturls.setHeat(elementFileInfoItem.children().get(2).html());
                        list.add(bturls);
                    }

                    Elements pageDatas = element.select("ul.pg");

                    Integer maxPage = 1;
                    //有分页数据
                    if(pageDatas.size() > 0)
                    {
                        for(Element pageItem : pageDatas.first().children())
                        {
                            Matcher mer = Pattern.compile("^[+-]?[0-9]+$").matcher(pageItem.html());
                            if(mer.find())
                            {
                                if(maxPage < Integer.parseInt(pageItem.html()))
                                {
                                    maxPage = Integer.parseInt(pageItem.html());
                                }
                            }
                        }
                        commonPage.setPageCount(maxPage);
                        commonPage.setCurrentCount(currentPage);
                    }
                    else
                    {
                       //无分页数据
                        commonPage.setPageCount(1);
                        commonPage.setCurrentCount(1);
                    }
                }
            }
            commonPage.setDataList(list);
        }catch (Exception e)
        {
            e.printStackTrace();
            commonPage.setCode(SearchConstants.CODE_FAIL);
            commonPage.setMessage("数据检索异常！");
        }
        return commonPage;
    }

}
